<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog" width="60%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             label-width="auto"
             :inline="true"
             status-icon>

      <el-form-item label="名称：" prop="name" style="width:98%;max-width: unset">
        <el-input v-model="formData.name" :readonly="readonly" maxlength="128" placeholder="请输入配置名称" show-word-limit/>
      </el-form-item>

      <el-form-item label="类型：" prop="type">
        <DictTag v-if="readonly" v-model="formData.type" :circle="false" dict-type="subsidy_config_type"/>
        <DictSelect v-else v-model="formData.type" dict-type="subsidy_config_type"/>
      </el-form-item>

      <el-form-item label="模式：" prop="mode">
        <DictTag v-if="readonly" v-model="formData.mode" :circle="false" dict-type="subsidy_config_mode"/>
        <DictSelect v-else v-model="formData.mode" dict-type="subsidy_config_mode"/>
      </el-form-item>

      <!-- 1.0 模式比例 -->
      <template v-if="formData.mode == 1">
        <el-form-item label="补贴比例：" prop="subsidy_ratio">
          <el-input-number v-model="formData.subsidy_ratio" :max="2" :min="0" :precision="4" :step="0.1" controls-position="right"/>
          <span v-if="formData.subsidy_ratio != undefined" class="tip">{{ toPercent(formData.subsidy_ratio) }}</span>
        </el-form-item>

        <el-form-item label="让利比例：" prop="rebate_ratio">
          <el-input-number v-model="formData.rebate_ratio" :max="0.9" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.rebate_ratio != undefined" class="tip">{{ toPercent(formData.rebate_ratio) }}</span>
        </el-form-item>

        <el-form-item label="推广奖金：" prop="promotion_ratio">
          <el-input-number v-model="formData.promotion_ratio" :max="0.3" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.promotion_ratio != undefined" class="tip">{{ toPercent(formData.promotion_ratio) }}</span>
        </el-form-item>

        <el-form-item label="联盟服务费：" prop="service_fee_ratio">
          <el-input-number v-model="formData.service_fee_ratio" :max="0.3" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.service_fee_ratio != undefined" class="tip">{{ toPercent(formData.service_fee_ratio) }}</span>
        </el-form-item>
      </template>

      <!-- 2.0 模式比例 -->
      <template v-if="formData.mode == 2">
        <el-form-item label="补贴比例：" prop="subsidy_ratio" v-form-item-tip="'补贴金额 = 实付金额 * 当前比例'">
          <el-input-number v-model="formData.subsidy_ratio" :max="2" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.subsidy_ratio != undefined" class="tip">{{ toPercent(formData.subsidy_ratio) }}</span>
        </el-form-item>

        <el-form-item label="消费金：" prop="gold_ratio" v-form-item-tip="'消费金 = 实付金额 * 让利总比 * 当前比例'">
          <el-input-number v-model="formData.gold_ratio" :max="1" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.gold_ratio != undefined" class="tip">{{ toPercent(formData.gold_ratio) }}</span>
        </el-form-item>

        <el-form-item label="让利总比：" prop="total_ratio">
          <el-input-number v-model="formData.total_ratio" :max="1" :min="0" :precision="4" :step="0.1" controls-position="right"/>
          <span v-if="formData.total_ratio != undefined" class="tip">{{ toPercent(formData.total_ratio) }}</span>
        </el-form-item>

        <el-divider border-style="dashed" content-position="left">以下比例合计 {{ toPercent(calculateRatio) }}</el-divider>

        <el-form-item label="锁粉佣金：" prop="inviter_ratio">
          <el-input-number v-model="formData.inviter_ratio" :max="0.5" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.inviter_ratio != undefined" class="tip">{{ toPercent(formData.inviter_ratio) }}</span>
        </el-form-item>

        <el-form-item label="经理：" prop="level_ratio1">
          <el-input-number v-model="formData.level_ratio1" :max="0.5" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.level_ratio1 != undefined" class="tip">{{ toPercent(formData.level_ratio1) }}</span>
        </el-form-item>

        <el-form-item label="创客/合伙人：" prop="level_ratio2">
          <el-input-number v-model="formData.level_ratio2" :max="0.5" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.level_ratio2 != undefined" class="tip">{{ toPercent(formData.level_ratio2) }}</span>
        </el-form-item>

        <el-form-item label="区代：" prop="region_ratio3">
          <el-input-number v-model="formData.region_ratio3" :max="0.5" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.region_ratio3 != undefined" class="tip">{{ toPercent(formData.region_ratio3) }}</span>
        </el-form-item>

        <el-form-item label="市代：" prop="region_ratio2">
          <el-input-number v-model="formData.region_ratio2" :max="0.5" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.region_ratio2 != undefined" class="tip">{{ toPercent(formData.region_ratio2) }}</span>
        </el-form-item>

        <el-form-item label="省代：" prop="region_ratio1">
          <el-input-number v-model="formData.region_ratio1" :max="0.5" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.region_ratio1 != undefined" class="tip">{{ toPercent(formData.region_ratio1) }}</span>
        </el-form-item>

        <el-form-item label="大区：" prop="big_region_ratio">
          <el-input-number v-model="formData.big_region_ratio" :max="0.5" :min="0" :precision="4" :step="0.0001" controls-position="right"/>
          <span v-if="formData.big_region_ratio != undefined" class="tip">{{ toPercent(formData.big_region_ratio) }}</span>
        </el-form-item>
      </template>

      <el-form-item label="描述：" style="width:98%;max-width: unset">
        <el-input v-model="formData.remark" :autosize="{ minRows: 2}" :maxlength="200" :readonly="readonly" placeholder="请输入描述" type="textarea"/>
      </el-form-item>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['subsidy:config:create', 'subsidy:config:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { toPercent } from '@/utils';
import { SubsidyConfig, subsidyConfigInfo, subsidyConfigSaveOrUpdate } from '@/api/api-subsidy.ts';
import { DictTag } from '@/components/dict-tag';
import { DictSelect } from '@/components/dict-select';

defineOptions({name: 'subsidy-config-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

/** 默认表单数据 */
const defaultForm: SubsidyConfig = <SubsidyConfig>{id: 0};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{required: true, message: '配置名称不能为空', trigger: 'blur'}],
  subsidy_ratio: [{required: true, message: '补贴比例不能为空', trigger: 'blur'}],
  rebate_ratio: [{required: true, message: '让利比例不能为空', trigger: 'blur'}],
  promotion_ratio: [{required: true, message: '推广奖金比例不能为空', trigger: 'blur'}],
  service_fee_ratio: [{required: true, message: '联盟服务费比例不能为空', trigger: 'blur'}],
  total_ratio: [{required: true, message: '让利总比例不能为空', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = computed(() => {
  return dialogMode.value == 1 || formData.value.id <= 0;
});

/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '补贴配置';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();

  // 加载数据
  if (id) {
    formLoading.value = true
    try {
      // 加载用户数据
      const {data} = await subsidyConfigInfo(id)
      formData.value = data;
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    subsidyConfigSaveOrUpdate(formData.value, isCreate.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

/** 计算总比值 */
const calculateRatio = computed(() => {
  let val = 0.00;
  if (formData.value.mode == 2) {
    val += formData.value.inviter_ratio || 0;
    val += formData.value.level_ratio1 || 0;
    val += formData.value.level_ratio2 || 0;
    val += formData.value.region_ratio3 || 0;
    val += formData.value.region_ratio2 || 0;
    val += formData.value.region_ratio1 || 0;
    val += formData.value.big_region_ratio || 0;
  }
  return val;
})

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-select {
    width: 200px;
  }

  .el-input-number {
    width: 160px;
  }

  .el-form--inline .el-form-item {
    width: 350px;
  }
}
</style>
